import React, { useState, useEffect } from 'react';
import {openNotification_util,checkdatavalid_util,fetchsync_normal_util,useCallbackState, fetchsync_util} from '../util/util.js'
import { useHistory } from 'react-router-dom';
import { PlusOutlined } from '@ant-design/icons';
import { Modal, Upload,Button } from 'antd';
import fetch from 'isomorphic-fetch'
import imageCompression from 'browser-image-compression';
var storage = window.localStorage;

//预览图片用
const getBase64 = (file) =>
new Promise((resolve, reject) => {
	const reader = new FileReader();
	reader.readAsDataURL(file);
	reader.onload = () => resolve(reader.result);
	reader.onerror = (error) => reject(error);
});

const Upload_hooks = (props) => {
	const history = useHistory();
	const [formdata, setFormData] = useCallbackState({tpurl:""});
	const [previewOpen, setPreviewOpen] = useState(false);
	const [previewImage, setPreviewImage] = useState('');
	const [previewTitle, setPreviewTitle] = useState('');
	const [filelistobj, setFilelistobj] = useCallbackState(()=>{
				var filelistinitarr=[];
		var tparr=props.initpxtpurl.split(",")
//若大于1说明是edit方法有初始图片。
		if(tparr.length>=1&&tparr[0]!=""){
			tparr.map((item ,index)=> {
				if(item!=""){
				const url="http://111.77.154.58:2233/"+item
				filelistinitarr.push({uid:item,url:url,name:item})	}
			else;	})
		}
		else;
		let nowfilelistobj = Object.assign({},filelistobj, { filelistitem:filelistinitarr});
		return nowfilelistobj
	});



	useEffect(() => {
		var filelistinitarr=[];
		var tparr=props.initpxtpurl === null?[]:props.initpxtpurl.split(",")
//若大于1说明是edit方法有初始图片。
if(tparr.length>=1&&tparr[0]!=""){
	tparr.map((item ,index)=> {
				const url="http://111.77.154.58:2233/"+item
				filelistinitarr.push({uid:item,url:url,name:item})		})
		}
		else;
		let nowfilelistobj = Object.assign({},filelistobj, { filelistitem:filelistinitarr});
		setFilelistobj(nowfilelistobj)

	}, [props.initpxtpurl]);


///通用上传单文件 重新改用单文件上传,新写法，解耦file与预览file列表
	const handleupload_beforeupload= async (file,filelistname,key,text)=>{    
		try {
			// Set compression options
			const options = {
				maxSizeMB: 1, // Maximum size in MB
				maxWidthOrHeight: 1920, // Max width or height
				useWebWorker: true, // Use web worker for faster compression
			};
	
			// Compress the image
			const compressedFile = await imageCompression(file, options);

			const compressedFileWithOriginalName = new File(
				[compressedFile],
				file.name,
				{ type: compressedFile.type }
			);
	
			// Proceed with the upload using the compressed file
			uploadimggetutl(compressedFileWithOriginalName, filelistname, key, text);
		} catch (error) {
			console.error("Error compressing the image:", error);
		}
		return false;

	} ;


//通用附件上传方法
	const uploadimggetutl=(file,filelistname,key,text)=>{
		const formData = new FormData();
		formData.append('files[]', file);
		fetch("/admin/common/uploadfs", {
			method: 'POST',mode: 'cors',credentials: 'include',body: formData,
			headers: {'Authorization':`Bearer ${storage.token}` }
		}).then(response =>
		{
			if(response.status == '4x0x1')
				{openNotification_util("权限认证过期，重新登陆！")}else 
			return response.text();
		}).then(data=>{
			data=JSON.parse(data);
			//返回的是保存好的文件名，还要拼接地址
			var url="http://111.77.154.58:2233/"+data.filename
			var fileobj={uid:data.filename,url:url,name:data.filename}
			var prevfilelist=filelistobj[filelistname];
			let nowfilelistobj = Object.assign({},filelistobj, { [filelistname]: [...prevfilelist,fileobj]});
			setFilelistobj(nowfilelistobj,()=>{
				let tpurl = "";
				nowfilelistobj[filelistname].map((item ,index)=> {
					tpurl=index==0?item.name+tpurl:item.name+","+tpurl
				});
				let nowformdata = Object.assign({}, formdata, { [key]:tpurl});
				setFormData(nowformdata,()=>{
					props.handleback(tpurl);
				})

			})
		});
	};


// 

//通用上传移除多文件，重构，改写原来单文件的移除方法·。
	const handleupload_beforeonremove_muti=(file,filelistname,key)=>{  
		var list=filelistobj[filelistname];
		const index = list.indexOf(file);
		const newFileList = list.slice();
		newFileList.splice(index, 1);
		let nowfilelistobj = Object.assign({}, filelistobj, { [filelistname]: newFileList});
		let tpurl = "";
		newFileList.map((item,index) => {
			tpurl=index==0?item.name+tpurl:item.name+","+tpurl
		});
		let nowformdata = Object.assign({}, formdata, { [key]: tpurl});
		setFormData(nowformdata,()=>{
			setFilelistobj(nowfilelistobj,()=>{
				props.handleback(tpurl);
			})
		})
		fetchsync_util("/admin/common/deleteFile", "DELETE", {file: file.name}, "text")
	}



//取消预览
	const handleCancel = () => setPreviewOpen(false);
//预览
	const handlePreview = async (file) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj);
		}
		setPreviewImage(file.url || file.preview);
		setPreviewOpen(true);
		setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
	};


	//console.log("子组件触发")
	return (
		<div style={{marginTop:"-0.15rem",textAlign:"left",backgrounColor:"red"}}>
		<Upload  accept=".pdf,image/*"   listType= 'picture-card' 
		capture="camera"
		beforeUpload={(file)=>handleupload_beforeupload(file,'filelistitem','tpurl','文本')} 
		fileList={filelistobj.filelistitem}
		onRemove={(file)=>handleupload_beforeonremove_muti(file,'filelistitem','tpurl')}
		onPreview={handlePreview}
		className="upload-list-inline"
		disabled={props.disabled ? true : false}
		>       <PlusOutlined /><br/> {props.title} </Upload>
		<Modal open={previewOpen} title={previewTitle} footer={null} onCancel={handleCancel}>
		<img
		alt="example"
		style={{
			width: '100%',
		}}
		src={previewImage}
		/>
		</Modal>
		</div>
		);
};

export default Upload_hooks;

//通用附件上传方法多图
// 	const uploadimggetutlmuti=async (filelistname,key,text,customfilelist)=>{
// 		const fileformData = new FormData();
// 		customfilelist.forEach(file => { 
// 			fileformData.append('培训现场图片', file);});
// 		fetch("/admin/common/uploadfsmulti", {
// 			method: 'POST',mode: 'cors',credentials: 'include',body: fileformData,
// 			headers: {'Authorization':`Bearer ${storage.token}` }
// 		}).then(response =>
// 		{
// 			if(response.status == '4x0x1')
// 				{openNotification_util("权限认证过期，重新登陆！")}else 
// 			return response.text();
// 		}).then(data=>{
// 			var prevfilelist=customfilelist;
// 			var retdataarr=data.split(",");
// 			for(var i=0;i<=retdataarr.length-1;i++){
// 				prevfilelist[i].url="http://111.77.154.58:2233/"+retdataarr[i]
// 			}
// 			let nowfilelistdata = Object.assign({}, filelistobj, { [filelistname]: [...prevfilelist]});
// 			let nowformdata = Object.assign({}, formdata, { [key]:data});
// 			setFormData(nowformdata,()=>{
// 				setFilelistobj(nowfilelistdata,()=>{
// 					//console.log(nowfilelistdata)

// 					props.handleback(data);
// 				})
// 			})
// 		})
// 	}




// //通用上传多文件
// 	const handleupload_beforeupload_muti=(file,filelistname,key,text)=>{    
// 		var prevfilelist=filelistobj[filelistname];
// 		let nowfilelistobj = Object.assign({},filelistobj, { [filelistname]: [...prevfilelist,file]});
// 		uploadimggetutlmuti(filelistname,key,text,nowfilelistobj[filelistname])
// 		return false;
// 	}